const Group = require('../models/Group');
const Activity = require('../models/Activity');
const User = require('../models/User');
const Joi = require('joi');

// 分组更新验证Schema
const updateMembersSchema = Joi.object({
  members: Joi.array().items(Joi.string().regex(/^[0-9a-fA-F]{24}$/)).required()
});

// 随机分组验证Schema
const randomGroupSchema = Joi.object({
  activityId: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required(),
  userIds: Joi.array().items(Joi.string().regex(/^[0-9a-fA-F]{24}$/)).required(),
  groupCount: Joi.number().integer().min(1).max(50).required()
});

// 获取分组列表
exports.getGroups = async (req, res) => {
  try {
    const { activityId } = req.query;

    if (!activityId) {
      return res.status(400).json({
        success: false,
        message: '缺少activityId参数'
      });
    }

    // 验证ID格式
    if (!activityId.match(/^[0-9a-fA-F]{24}$/)) {
      return res.status(400).json({
        success: false,
        message: '无效的活动ID'
      });
    }

    // 执行查询
    const groups = await Group.find({ activityId })
      .populate('members', 'username name status');

    res.status(200).json({
      success: true,
      data: {
        groups
      }
    });
  } catch (error) {
    console.error('获取分组列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : {}
    });
  }
};

// 更新分组成员
exports.updateGroupMembers = async (req, res) => {
  try {
    const { id } = req.params;
    const { members } = req.body;

    // 验证ID格式
    if (!id.match(/^[0-9a-fA-F]{24}$/)) {
      return res.status(400).json({
        success: false,
        message: '无效的分组ID'
      });
    }

    // 验证数据
    const { error, value } = updateMembersSchema.validate({ members });
    if (error) {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        error: error.details[0].message
      });
    }

    // 检查分组是否存在
    const group = await Group.findById(id);
    if (!group) {
      return res.status(404).json({
        success: false,
        message: '分组不存在'
      });
    }

    // 更新分组成员
    const updatedGroup = await Group.findByIdAndUpdate(
      id,
      { $set: { members: value.members } },
      { new: true }
    ).populate('members', 'username name status');

    res.status(200).json({
      success: true,
      message: '分组成员更新成功',
      data: {
        group: updatedGroup
      }
    });
  } catch (error) {
    console.error('更新分组成员错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : {}
    });
  }
};

// 随机分组
exports.randomGrouping = async (req, res) => {
  try {
    const { activityId, userIds, groupCount } = req.body;

    // 验证数据
    const { error, value } = randomGroupSchema.validate({ activityId, userIds, groupCount });
    if (error) {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        error: error.details[0].message
      });
    }

    // 验证活动是否存在
    const activity = await Activity.findById(activityId);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }

    // 验证用户ID列表
    const users = await User.find({ _id: { $in: userIds } });
    if (users.length !== userIds.length) {
      return res.status(400).json({
        success: false,
        message: '部分用户ID无效'
      });
    }

    // Fisher-Yates 洗牌算法实现随机分组
    const shuffledUsers = [...userIds];
    for (let i = shuffledUsers.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffledUsers[i], shuffledUsers[j]] = [shuffledUsers[j], shuffledUsers[i]];
    }

    // 创建分组
    const groups = [];
    const usersPerGroup = Math.floor(shuffledUsers.length / groupCount);
    const remainingUsers = shuffledUsers.length % groupCount;

    // 删除现有分组
    await Group.deleteMany({ activityId });

    // 创建新的分组
    for (let i = 0; i < groupCount; i++) {
      const startIndex = i * usersPerGroup;
      let endIndex = startIndex + usersPerGroup;
      
      // 分配剩余用户
      if (i < remainingUsers) {
        endIndex += 1;
      }
      
      const groupMembers = shuffledUsers.slice(startIndex, endIndex);
      
      const group = new Group({
        name: `第${i + 1}组`,
        activityId,
        members: groupMembers
      });
      
      await group.save();
      groups.push(group);
    }

    // 填充分组成员信息
    const populatedGroups = await Group.find({ activityId })
      .populate('members', 'username name status');

    res.status(200).json({
      success: true,
      message: '随机分组完成',
      data: {
        groups: populatedGroups
      }
    });
  } catch (error) {
    console.error('随机分组错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : {}
    });
  }
};

// 创建分组
exports.createGroup = async (req, res) => {
  try {
    const { name, activityId, members = [] } = req.body;

    // 验证活动是否存在
    const activity = await Activity.findById(activityId);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }

    // 验证用户
    if (members.length > 0) {
      const users = await User.find({ _id: { $in: members } });
      if (users.length !== members.length) {
        return res.status(400).json({
          success: false,
          message: '部分用户ID无效'
        });
      }
    }

    // 创建分组
    const group = new Group({
      name,
      activityId,
      members
    });

    await group.save();

    // 填充分组成员信息
    const populatedGroup = await Group.findById(group._id)
      .populate('members', 'username name status');

    res.status(201).json({
      success: true,
      message: '分组创建成功',
      data: {
        group: populatedGroup
      }
    });
  } catch (error) {
    console.error('创建分组错误:', error);
    
    if (error.name === 'ValidationError') {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        error: Object.values(error.errors).map(err => err.message)
      });
    }
    
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : {}
    });
  }
};

// 删除分组
exports.deleteGroup = async (req, res) => {
  try {
    const { id } = req.params;

    // 验证ID格式
    if (!id.match(/^[0-9a-fA-F]{24}$/)) {
      return res.status(400).json({
        success: false,
        message: '无效的分组ID'
      });
    }

    // 检查分组是否存在
    const group = await Group.findById(id);
    if (!group) {
      return res.status(404).json({
        success: false,
        message: '分组不存在'
      });
    }

    // 删除分组
    await Group.findByIdAndDelete(id);

    res.status(200).json({
      success: true,
      message: '分组删除成功'
    });
  } catch (error) {
    console.error('删除分组错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : {}
    });
  }
};